import 'package:flutter/material.dart';

/// Dart类和对象示例
class ClassesObjectsExample extends StatefulWidget {
  const ClassesObjectsExample({super.key});

  @override
  State<ClassesObjectsExample> createState() => _ClassesObjectsExampleState();
}

class _ClassesObjectsExampleState extends State<ClassesObjectsExample> {
  String result = '点击下方按钮查看类和对象示例';

  void _demonstrateBasicClass() {
    // 使用外部定义的Person类
    var person = const _Person('张三', 25);

    setState(() {
      result =
          '''
【基本类定义】

class Person {
  String name;
  int age;
  
  // 构造函数
  Person(this.name, this.age);
  
  // 方法
  String introduce() {
    return '我是\$name，今年\$age岁';
  }
}

创建对象:
var person = Person('张三', 25);

使用:
person.name = ${person.name}
person.age = ${person.age}
person.introduce() = ${person.introduce()}
      ''';
    });
  }

  void _demonstrateConstructors() {
    // 使用外部定义的User类
    var user1 = _User('Alice', 25, 'alice@example.com');
    var user2 = _User.guest();
    var user3 = _User.fromMap({'name': 'Bob', 'age': 30, 'email': 'bob@example.com'});

    setState(() {
      result =
          '''
【构造函数】

1. 标准构造函数:
User(this.name, this.age, [this.email]);

2. 命名构造函数:
User.guest() : name = 'Guest', age = 0;

User.fromMap(Map<String, dynamic> map)
    : name = map['name'], age = map['age'];

创建对象:
${user1.info()}
${user2.info()}
${user3.info()}

常见命名构造函数:
• .fromJson() - 从JSON创建
• .empty() - 创建空对象
• .copy() - 复制对象
      ''';
    });
  }

  void _demonstrateInheritance() {
    // 使用外部定义的Dog类
    var dog = _Dog('旺财', '金毛');

    setState(() {
      result =
          '''
【继承】

// 父类
class Animal {
  String name;
  Animal(this.name);
  
  String makeSound() => '\$name 发出声音';
}

// 子类
class Dog extends Animal {
  String breed;
  
  Dog(super.name, this.breed);
  
  @override
  String makeSound() => '\$name 汪汪汪！';
}

使用:
var dog = Dog('旺财', '金毛');

调用:
dog.name = ${dog.name}
dog.breed = ${dog.breed}
dog.makeSound() = ${dog.makeSound()}
dog.getBreed() = ${dog.getBreed()}

特点:
• extends 关键字继承
• super 访问父类
• @override 重写方法
      ''';
    });
  }

  void _demonstrateMixins() {
    // 使用外部定义的Bird和Duck类
    var bird = _Bird('麻雀');
    var duck = _Duck('唐老鸭');

    setState(() {
      result =
          '''
【Mixin混入】
Mixin用于复用代码，类似多重继承但更灵活。

定义Mixin:
mixin CanFly {
  void fly() => '我会飞！';
}

mixin CanSwim {
  void swim() => '我会游泳！';
}

使用Mixin:
class Bird with CanFly {
  String name;
  Bird(this.name);
}

class Duck with CanFly, CanSwim {
  String name;
  Duck(this.name);
}

结果:
${bird.name}: ${bird.fly()}
${duck.name}: ${duck.fly()} 和 ${duck.swim()}

优势:
• 避免多重继承的问题
• 灵活组合功能
• 代码复用
      ''';
    });
  }

  void _demonstrateGetterSetter() {
    // 使用外部定义的Rectangle类
    var rect = _Rectangle(10, 5);
    double originalArea = rect.area;
    rect.area = 100;

    setState(() {
      result =
          '''
【Getter和Setter】

class Rectangle {
  double width;
  double height;
  
  // Getter - 计算属性
  double get area => width * height;
  
  // Setter - 设置时执行逻辑
  set area(double value) {
    // 调整宽高
  }
}

使用:
var rect = Rectangle(10, 5);

Getter:
rect.area // 像访问属性一样
原始面积: $originalArea

Setter:
rect.area = 100; // 像设置属性一样
新的尺寸: ${rect.info}
新的面积: ${rect.area.toStringAsFixed(1)}

特点:
• 看起来像属性，实际是方法
• 可以添加验证逻辑
• 计算属性不占用内存
      ''';
    });
  }

  void _demonstrateAbstractClass() {
    setState(() {
      result = '''
【抽象类】
抽象类不能实例化，用于定义接口和共享代码。

定义:
abstract class Shape {
  // 抽象方法（没有实现）
  double calculateArea();
  
  // 具体方法（有实现）
  void printInfo() {
    print('面积: \${calculateArea()}');
  }
}

实现:
class Circle extends Shape {
  double radius;
  
  Circle(this.radius);
  
  @override
  double calculateArea() {
    return 3.14 * radius * radius;
  }
}

class Rectangle extends Shape {
  double width, height;
  
  Rectangle(this.width, this.height);
  
  @override
  double calculateArea() {
    return width * height;
  }
}

使用:
Shape circle = Circle(5);
Shape rect = Rectangle(4, 6);

circle.calculateArea(); // 78.5
rect.calculateArea(); // 24

特点:
• 定义接口契约
• 可以包含具体实现
• 子类必须实现抽象方法
      ''';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 类和对象'), backgroundColor: Theme.of(context).colorScheme.inversePrimary),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 说明卡片
            Card(
              color: Colors.indigo.shade50,
              child: const Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text('🏛️ 类和对象概述', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                    SizedBox(height: 8),
                    Text(
                      'Dart是面向对象的语言：\n'
                      '• 类：定义对象的模板\n'
                      '• 构造函数：创建对象\n'
                      '• 继承：extends扩展父类\n'
                      '• Mixin：with复用代码\n'
                      '• Getter/Setter：计算属性\n'
                      '• 抽象类：定义接口',
                      style: TextStyle(fontSize: 14),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),

            // 代码示例区域
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8)),
              child: const Text('''// 类定义
class Person {
  String name;
  int age;
  
  Person(this.name, this.age);
  
  void greet() => print('Hello');
}

// 继承
class Student extends Person {
  Student(super.name, super.age);
}

// Mixin
mixin CanFly {
  void fly() { }
}

class Bird with CanFly { }

// Getter/Setter
double get area => width * height;
set area(double v) { }''', style: TextStyle(fontFamily: 'monospace', fontSize: 13)),
            ),
            const SizedBox(height: 16),

            // 交互按钮
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(onPressed: _demonstrateBasicClass, icon: const Icon(Icons.class_), label: const Text('基本类')),
                ElevatedButton.icon(onPressed: _demonstrateConstructors, icon: const Icon(Icons.construction), label: const Text('构造函数')),
                ElevatedButton.icon(onPressed: _demonstrateInheritance, icon: const Icon(Icons.account_tree), label: const Text('继承')),
                ElevatedButton.icon(onPressed: _demonstrateMixins, icon: const Icon(Icons.merge_type), label: const Text('Mixin')),
                ElevatedButton.icon(
                  onPressed: _demonstrateGetterSetter,
                  icon: const Icon(Icons.settings),
                  label: const Text('Getter/Setter'),
                ),
                ElevatedButton.icon(onPressed: _demonstrateAbstractClass, icon: const Icon(Icons.api), label: const Text('抽象类')),
              ],
            ),
            const SizedBox(height: 16),

            // 结果展示区域
            Card(
              elevation: 4,
              child: Container(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                constraints: const BoxConstraints(minHeight: 150),
                child: Text(result, style: const TextStyle(fontSize: 14, fontFamily: 'monospace')),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 辅助类定义
class _Person {
  final String name;
  final int age;

  const _Person(this.name, this.age);

  String introduce() {
    return '我是$name，今年$age岁';
  }
}

class _User {
  final String name;
  final int age;
  final String? email;

  _User(this.name, this.age, [this.email]);

  _User.guest() : name = 'Guest', age = 0, email = null;

  _User.fromMap(Map<String, dynamic> map) : name = map['name'], age = map['age'], email = map['email'];

  String info() => 'User: $name, Age: $age, Email: ${email ?? "无"}';
}

class _Animal {
  final String name;
  _Animal(this.name);

  String makeSound() => '$name 发出声音';
}

class _Dog extends _Animal {
  final String breed;

  _Dog(String name, this.breed) : super(name);

  @override
  String makeSound() => '$name 汪汪汪！';

  String getBreed() => '品种: $breed';
}

mixin _CanFly {
  String fly() => '我会飞！';
}

mixin _CanSwim {
  String swim() => '我会游泳！';
}

class _Bird with _CanFly {
  final String name;
  _Bird(this.name);
}

class _Duck with _CanFly, _CanSwim {
  final String name;
  _Duck(this.name);
}

class _Rectangle {
  double width;
  double height;

  _Rectangle(this.width, this.height);

  double get area => width * height;

  set area(double value) {
    double ratio = width / height;
    height = (value / ratio);
    width = value / height;
  }

  String get info => 'Rectangle(${width.toStringAsFixed(1)} × ${height.toStringAsFixed(1)})';
}
